package com.mimo.logic.room.grpc;

import java.util.Collection;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;

import com.google.protobuf.Any;
import com.google.protobuf.BoolValue;
import com.google.protobuf.StringValue;
import com.mimo.common.logic.code.StatusCode;
import com.mimo.common.rpc.proto.BaseResponseProto.BaseResponse;
import com.mimo.common.rpc.proto.BaseResponseProto.Plurality;
import com.mimo.common.rpc.proto.LogicRoomProxyGrpc;
import com.mimo.common.rpc.proto.LogicRoomRpc.ClientRoomOpsMessage;
import com.mimo.logic.config.heartbeat.annotation.ExcludeHeartbeat;
import com.mimo.logic.room.service.IRoomService;

import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;

@GrpcService
public class LogicRoomGrpc extends LogicRoomProxyGrpc.LogicRoomProxyImplBase {

  @Autowired
  private IRoomService roomService;

  @Override
  public void listRooms(StringValue request, StreamObserver<BaseResponse> responseObserver) {
    Collection<String> rooms = roomService.listJointRooms(request.getValue());
    BaseResponse resp = BaseResponse.newBuilder().setPluralityValue(Plurality.newBuilder()
        .addAllItems(rooms.stream().map(StringValue::of).map(Any::pack).collect(Collectors.toList()))).build();
    responseObserver.onNext(resp);
    responseObserver.onCompleted();
  }

  @Override
  public void join(ClientRoomOpsMessage request, StreamObserver<BaseResponse> responseObserver) {
    StatusCode statusCode = roomService.add(request.getRoomId(), request.getUserId());
    responseObserver.onNext(statusCode.toResp());
    responseObserver.onCompleted();
  }

  @Override
  public void leave(ClientRoomOpsMessage request, StreamObserver<BaseResponse> responseObserver) {
    roomService.leave(request.getRoomId(), request.getUserId());
    responseObserver.onNext(StatusCode.getSuccessInstance());
    responseObserver.onCompleted();
  }

  @ExcludeHeartbeat
  @Override
  public void isMemberOf(ClientRoomOpsMessage request, StreamObserver<BoolValue> responseObserver) {
    BoolValue bv = BoolValue.of(roomService.isMemberOf(request.getRoomId(), request.getUserId()));
    responseObserver.onNext(bv);
    responseObserver.onCompleted();
  }

}
